<template>
  <div 
    class="video-container" 
    @mouseenter="showControls = true" 
    @mouseleave="showControls = false"
  >
    <!-- 视频播放器 -->
    <video
      ref="videoPlayer"
      :src="effectiveUrl"
      crossorigin="anonymous"
      playsinline
      preload="auto"
      @loadeddata="handleLoaded"
      @play="handlePlay"
      @pause="handlePause"
      @ended="handleEnded"
      @error="handleError"
    ></video>

    <!-- 播放完成覆盖层 -->
    <div 
      v-if="showEndOverlay" 
      class="end-overlay"
      :style="{ backgroundImage: `url(${endBackground})` }"
      @click="replayVideo"
    >
    </div>

    <!-- 控制按钮 -->
    <transition name="fade">
      <div v-show="showControls" class="control-overlay">
        <el-button
          circle
          class="control-button"
          :icon="isPlaying ? VideoPause : VideoPlay"
          @click.stop="togglePlay"
        />
      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onUnmounted } from 'vue'
import { VideoPlay, VideoPause } from '@element-plus/icons-vue'

const props = defineProps({
  videoUrl: {
    type: String,
    required: true,
    validator: (url: string) => url.startsWith('http')
  },
  endBackground: {
    type: String,
    default: '' // 播放完成后的背景图URL
  },
  autoplay: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['ready', 'error', 'ended'])

const videoPlayer = ref<HTMLVideoElement | null>(null)
const effectiveUrl = ref('')
const isReady = ref(false)
const isPlaying = ref(false)
const showControls = ref(false)
const showEndOverlay = ref(false)

// 安全设置视频源
const setVideoSource = async () => {
  showEndOverlay.value = false
  isReady.value = false
  
  if (!props.videoUrl) {
    emit('error', new Error('EMPTY_SRC'))
    return
  }

  effectiveUrl.value = props.videoUrl
  await nextTick()
  
  if (videoPlayer.value) {
    videoPlayer.value.load()
  }
}

// 播放控制
const togglePlay = () => {
  if (!videoPlayer.value) return
  
  if (isPlaying.value) {
    videoPlayer.value.pause()
  } else {
    videoPlayer.value.play().catch(err => {
      console.warn('播放失败:', err)
      videoPlayer.value!.muted = true
      videoPlayer.value!.play()
    })
  }
}

// 重新播放
const replayVideo = () => {
  if (videoPlayer.value) {
    videoPlayer.value.currentTime = 0
    videoPlayer.value.play()
    showEndOverlay.value = false
  }
}

// 事件处理
const handleLoaded = () => {
  isReady.value = true
  if (props.autoplay) {
    videoPlayer.value?.play()
  }
}

const handlePlay = () => {
  isPlaying.value = true
  showEndOverlay.value = false
}

const handlePause = () => {
  isPlaying.value = false
}

const handleEnded = () => {
  showEndOverlay.value = true
  emit('ended')
}

const handleError = (e: Event) => {
  const error = videoPlayer.value?.error || new Error('UNKNOWN_ERROR')
  console.error('视频错误:', error)
  emit('error', error)
}

// 监听变化
watch(() => props.videoUrl, setVideoSource, { immediate: true })

// 清理
onUnmounted(() => {
  if (videoPlayer.value) {
    videoPlayer.value.pause()
    videoPlayer.value.src = ''
    videoPlayer.value.load()
  }
})
</script>

<style scoped>
.video-container {
  position: relative;
  width: 100%;
  aspect-ratio: 16/9;
  background: #000;
  overflow: hidden;
  cursor: pointer;
}

video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

/* 控制按钮 */
.control-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.3);
}

.control-button {
  width: 60px;
  height: 60px;
  font-size: 24px;
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.8);
  color: white;
  
  &:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(1.1);
  }
}

/* 播放完成覆盖层 */
.end-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.7);
  background-blend-mode: overlay;
}

.replay-button {
  width: 80px;
  height: 80px;
  font-size: 32px;
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.8);
  color: white;
  
  &:hover {
    background: var(--el-color-primary);
    transform: scale(1.1);
  }
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>